package com.jetlion.dynamic;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import com.jetlion.dynamic.receiver.MyReceiver;

public class MainActivity extends AppCompatActivity {

    private MyReceiver myReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initWidget();
        myReceiver = new MyReceiver();
        //设置广播接收的action name
        IntentFilter intentFilter = new IntentFilter("android.intent.action.receiverdemo");
        //注册广播
        registerReceiver(myReceiver, intentFilter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (myReceiver != null) {
            //注销广播接收器
            unregisterReceiver(myReceiver);
            myReceiver = null;
        }
    }

    private void initWidget() {

        Button button = findViewById(R.id.send_btn);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setAction("android.intent.action.receiverdemo");
                intent.putExtra("msg", "this is a broadcast");
                MainActivity.this.sendBroadcast(intent);
            }
        });

    }
}